const js2xmlparser = require("js2xmlparser");
const xmlAttrKey = "attr0123";
const xmlValueKey = "value0123";

const requireDeletedMapping = {
    "_id": true,
    "__v": true,
    "updatedAt": true,
    "createdAt": true,
    "SellerId": true,
    "MarketplaceId": true,
    "BrowsePathById": true,
    "Status": true,
    "user": true,
    "Category": true,
    "ChildCategory": true,
    "StatusTime": true,
};

function processObjectRecursively(obj){
    for (const k in obj){
        if (k === xmlAttrKey){
            obj["@"] = obj[xmlAttrKey]; // 在js2xmlparser中@符号表示xml attribute，而我们因为mongodb的限制不能用此类符号，所以这里做这个转换
            delete obj[xmlAttrKey];
        }
        else if (k === xmlValueKey){
            obj["#"] = obj[xmlValueKey]; // 同上，在js2xmlparser中用#符号表示xml一个节点的value
            delete obj[xmlValueKey];
        }
        // if (obj[k] === null || obj[k] === undefined || obj[k] === "") {  // 删除某些节点值为null
        //     delete obj[k];
        // }
        // if (typeof obj[k] == "object" && Object.keys(obj[k]).length === 0) {
        //     delete obj[k];
        // }
        if (typeof obj[k] == "object" && obj[k] !== null) {
            processObjectRecursively(obj[k]);
        } else {
            if (requireDeletedMapping[k]){ // 删除并过滤掉amazon不认可的节点
                delete obj[k];
            }
            // if (k === "_id"){
            //     delete obj["_id"];
            // }
        }
    }
}
function tryClearEmptyElement(obj, k){
  if (obj[k] === null || obj[k] === undefined || obj[k] === "") {  // 删除某些节点值为null
    delete obj[k];
  }
  if (typeof obj[k] == "object" && Object.keys(obj[k]).length === 0) {
    delete obj[k];
  }
}
function clearEmptyElementRecursively(obj) {
  for (const k in obj) {
    if (typeof obj[k] == "object" && (obj[k] != null || obj[k] != undefined && Object.keys(obj[k]).length > 0)) {
      clearEmptyElementRecursively(obj[k]);
      tryClearEmptyElement(obj, k);
    } else {
      tryClearEmptyElement(obj, k);
    }
  }
}

let m = function(root, jsObj) {
  processObjectRecursively(jsObj);
  clearEmptyElementRecursively(jsObj);
    // JM: 这里必须做第二轮删除，因为某些嵌套节点的子节点==null在第一轮被清除后，会造成其父节点变为null
    // 这里先删除两轮，其实还有问题，如果是三层嵌套可能还有问题，这个后面再说
    // processObjectRecursively(jsObj);
    // processObjectRecursively2(jsObj);
    // let root = Object.keys(jsObj)[0];
    // let children = root.keys(root);
    // for (let k in children) {
    //     jsObj.k = root.k;
    // }
    return js2xmlparser.parse(root, jsObj);
};

module.exports = m;